package org.example.controller;

import antlr.Token;
import cn.hutool.core.io.FileUtil;
import org.example.common.annotation.Log;
import org.example.common.enums.BusinessType;
import org.example.common.result.Result;
import org.example.common.util.FileUploadUtils;
import org.example.common.util.MimeTypeUtils;
import org.example.common.util.UserContext;
import org.example.config.LqsConfig;
import org.example.entity.Account;
import org.example.entity.TFile;
import org.example.entity.UserDTO;
import org.example.service.UserService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * 用户相关接口，增删改查
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户查询自己的接口,返回除了密码的数据，service中相应的方法可以用在个人信息那
     * @return user
     */
     @GetMapping()
     public Result selectUserMsg(){
         UserDTO userInfo =userService.selectUserMsg(UserContext.getUser().getId());
        return Result.success(userInfo);
     }

    /**
     * 修改信息
     * @return
     */
     @PostMapping("/updateUser")
     public Result updateUser(@RequestBody UserDTO userDTO ){
         if(userService.upDateUserInfo(userDTO)){
             return Result.success();
         }else{
             return Result.error();
         }

     }

    /**
     * 查询个人上传的所有文件
     * @return List
     */
    @GetMapping("/selectFileList")
    public Result selectFileList(){
        Account user= UserContext.getUser();
        List<TFile> result=userService.selectFileList(user.getId());
        return Result.success(result);
    }

    /**
     * 上传头像
     */
//    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public Result avatar( MultipartFile file) throws Exception {

        if(!file.isEmpty()){
            int userid=UserContext.getUserId();//先得到当前用户
            //再查一下头像
            UserDTO userInfo=userService.selectUserMsg(userid);
            String oldAvatar=userInfo.getAvatarFile();
            String avatar =  FileUploadUtils.upload(LqsConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION, true);//得到文件的路径
            if(userService.updateUserAvatar(userid,avatar)){
                if(oldAvatar != null&&!oldAvatar.isEmpty()){
                    FileUtil.del(oldAvatar);//删除源文件
                }
            }
            return Result.success();
        }
        return Result.error("上传图片异常");
    }



}
